/*
 * @Descripttion:
 * @version: 1.0.0
 * @Author: YinJianFeng
 * @Date: 2024-03-29 10:15:27
 */
import { wsApi } from '@app-cad/server';
import { clearMaterialByDxid, setMaterialByDxid } from './modelHandler';
import { dataManager } from '@app-cad/module';

export class MaterialSetter {
  static instance: MaterialSetter;
  private constructor() {}

  public static getInstance(): MaterialSetter {
    if (!MaterialSetter.instance) {
      MaterialSetter.instance = new MaterialSetter();
    }
    return MaterialSetter.instance;
  }

  public async newMaterial(): Promise<any> {
    const result = await wsApi.addMaterials();
    await this.reloadMaterials();
    return result;
  }
  public async editMaterial(material: any) {
    console.log('editMaterial', material);
    const result = await wsApi.editMaterials(material);
    await this.reloadMaterials();
    const dxid = material['dxid'];
    const faceIndex = material['faceIndex'];
    const materialId = material['id'];
    if (dxid) {
      setMaterialByDxid(dxid, faceIndex, materialId);
    }
    return result;
  }
  public setMaterial(dxid: string, faceIndex: number, materialId: number) {
    setMaterialByDxid(dxid, faceIndex, materialId);
    return wsApi.setMaterials(dxid, faceIndex, materialId);
  }
  public async cleanMaterial(dxid: string, faceIndex: number) {
    clearMaterialByDxid(dxid, faceIndex);
    return wsApi.setMaterials(dxid, faceIndex, -1);
  }

  private async reloadMaterials() {
    const materials = await wsApi.getDocumentMaterials();
    dataManager.setMaterials(materials);
  }
}

export const materialSetter = MaterialSetter.getInstance();
